package com.example.springboot_mongo.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jxd
 * @since 2020/2/29 21:09
 */
@Controller
@RequestMapping("/qr")
public class QRController {

    @GetMapping("/img")
   public void gen(HttpServletResponse response) throws IOException, WriterException {
       response.setContentType("image/png");
       ServletOutputStream outputStream = response.getOutputStream();
       outputStream.write(imageBytes());
       outputStream.flush();
       outputStream.close();
   }


   private byte [] imageBytes() throws IOException, WriterException {
       QRCodeWriter qrCodeWriter = new QRCodeWriter();

       Map<EncodeHintType, Object> hints = new HashMap<>();
       hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
       hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");

       BitMatrix bitMatrix = qrCodeWriter.encode("https://www.felord.cn", BarcodeFormat.QR_CODE, 80, 80,hints);

       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
       MatrixToImageWriter.writeToStream(bitMatrix,"png",byteArrayOutputStream);
      return byteArrayOutputStream.toByteArray();
   }

}